package com.hooker.plugins;

import android.content.BroadcastReceiver;
import android.content.Context;

import com.hooker.base.BaseXposedLoader;
import com.hooker.common.Reflect;
import com.hooker.common.Reflection;

import java.util.Arrays;

import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.callbacks.XC_LoadPackage;

public class ReceiverEntry extends BaseXposedLoader {

    public ReceiverEntry(Context context, XC_LoadPackage.LoadPackageParam loadParams) {
        super(context, loadParams);
    }

    @Override
    public void hook(Object... calls) {
        log("ReceiverEntry hook ");
        try {
            hookAllMethod(loadParams.classLoader.loadClass("android.app.ContextImpl"), "registerReceiver", new XC_MethodHook() {
                @Override
                protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                    super.beforeHookedMethod(param);
                    log("registerReceiver "+ Arrays.toString(param.args));
                    Context context = (Context) param.thisObject;
                    Object getOuterContext = Reflection.call(context, "android.app.ContextImpl", "getOuterContext", new Class[]{});
                    log("registerReceiver getOuterContext :"+ getOuterContext);
                }
            });

            hookMethod(loadParams.classLoader.loadClass("android.app.ContextImpl"), "unregisterReceiver", BroadcastReceiver.class, new XC_MethodHook() {
                @Override
                protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                    super.beforeHookedMethod(param);
                    log("unregisterReceiver "+ Arrays.toString(param.args));
                    Context context = (Context) param.thisObject;
                    Object getOuterContext = Reflection.call(context, "android.app.ContextImpl", "getOuterContext", new Class[]{});
                    log("unregisterReceiver getOuterContext :"+ getOuterContext);
                    for (StackTraceElement stackTraceElement : Thread.currentThread().getStackTrace()) {
                        log("unregisterReceiver: "+stackTraceElement);
                    }
                }
            });
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
